package cn.jiyun.controller;
import cn.jiyun.common.AutoLogs;
import cn.jiyun.common.AutoLogs2;
import cn.jiyun.mapper.RoleMapper;
import cn.jiyun.pojo.Department;
import cn.jiyun.pojo.Role;
import cn.jiyun.pojo.User;
import cn.jiyun.service.DepartmentService;
import cn.jiyun.service.UserService;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.PutObjectResult;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.api.R;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import cn.jiyun.common.config.Result;
import org.springframework.web.multipart.MultipartFile;
import java.io.InputStream;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Random;
import java.util.UUID;
import java.util.concurrent.TimeUnit;


@RestController
@RequestMapping("user")
@CrossOrigin
public class UserController {
    @Autowired
    private UserService userService;
    @Autowired
    private RoleMapper roleMapper;
    @Autowired
    private DepartmentService departmentService;
    @Autowired
    private RedisTemplate redisTemplate;

    @RequestMapping("/sendCode") //忘记密码
    public Result sendCode(String phone){
        LambdaQueryWrapper<User> qr = new LambdaQueryWrapper<User>();
        qr.eq(User::getPhone,phone);
        User one = userService.getOne(qr);
        if(one==null){
            return Result.fail("手机号不存在");
        }
        Random r = new Random();
        int i = r.nextInt(10000);
        if (i<1000){
            i = i+1000;
        }
        String jsonString=i+"";
        redisTemplate.boundHashOps("code").put(phone,jsonString);
        redisTemplate.opsForValue().set(phone,jsonString,1, TimeUnit.MINUTES);
        return Result.ok(jsonString);
    }

    @RequestMapping("/sendCode2")
    public Result sendCode2(String phone){
        Random r = new Random();
        int i = r.nextInt(10000);
        if (i<1000){
            i = i+1000;
        }
        String jsonString=i+"";
        redisTemplate.opsForValue().set(phone,jsonString,1, TimeUnit.MINUTES);
        return Result.ok(jsonString);
    }

    @RequestMapping("findbumen")
    public Result findbumen(Department department){
        List<Department> departmentList = departmentService.tab(department);
        return Result.ok(departmentList);
    }

    @RequestMapping("/updatePassword")
    public Result updatePassword(Integer id,String password){
        User user = userService.getById(id);
        user.setPassword(password);
        userService.updateById(user);
        return Result.ok("修改成功！");
    }

    @RequestMapping("/updatePassword2")
    public Result updatePassword2(String phone,String password){
        LambdaQueryWrapper<User> qr = new LambdaQueryWrapper<User>();
        qr.eq(User::getPhone,phone);
        User user = userService.getOne(qr);
        user.setPassword(password);
        userService.updateById(user);
        return Result.ok("修改成功！");
    }

    @RequestMapping("/updatePassword3")
    public Result updatePassword3(String phone,String password){
        User user = new User();
        user.setPhone(phone);
        user.setPassword(password);
        user.setUsername(password);
        user.setYid(3);
        userService.save(user);
        return Result.ok("注册成功！");
    }

    @RequestMapping("/login")
    @AutoLogs2(value = "登录操作", loggingtype  = 0)
    public Result login(@RequestBody User user){
        LambdaQueryWrapper<User> qr = new LambdaQueryWrapper<>();
        qr.eq(User::getUsername,user.getUsername()).or().eq(User::getPhone,user.getUsername());
        User one = userService.getOne(qr);
        if (one==null){
            return Result.fail("账号或手机号不存在！");
        }
        if (!one.getPassword().equals(user.getPassword())){
            return Result.fail("密码错误！");
        }
        return Result.ok(one);
    }

    @RequestMapping("/findPage")
    public Result findPage(Integer pageNum, Integer pageSize, @RequestBody User user){
        Page page=userService.findpage(pageNum,pageSize,user);
        return  Result.ok(page);
    }

    @RequestMapping("/add")
    @AutoLogs(value = "用户添加操作", loggingtype  = 0)
    public Result add(@RequestBody User user){
        user.setTime(LocalDateTime.now());
        user.setCrname("admin");
        user.setPassword("123");
        user.setCaId(1);
        userService.saveOrUpdate(user);
        return Result.ok("添加成功！");
    }

    @RequestMapping("/findById")
    public Result findById(Integer id){
        User user=userService.getById(id);
        return Result.ok(user);
    }

    @RequestMapping("/deleteById")
    @AutoLogs(value = "用户删除操作", loggingtype  = 0)
    public Result deleteById(Integer id){
        try {
            userService.removeById(id);
            return Result.ok("删除成功！");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return Result.ok("删除成功！");
    }

    @RequestMapping("findAll")
    public Result findAll(){
       List<Role> list =  roleMapper.selectList(null);
       return Result.ok(list);
    }

    @Value("${aliyun.endpoint}")
    private String endpoint;
    @Value("${aliyun.keyid}")
    private String keyid;
    @Value("${aliyun.keysecret}")
    private String keysecret;
    @Value("${aliyun.bucketname}")
    private String bucketname;

    @RequestMapping("tp")
//    @AutoLogs(value = "服务管理图片上传操作", loggingtype  = 0)
    public String fileUpload(MultipartFile file) {

        String url = "";
        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, keyid, keysecret);
        try {
            // 创建PutObjectRequest对象。
            InputStream inputStream = file.getInputStream();
            String originalFilename = file.getOriginalFilename();

            String replace = UUID.randomUUID().toString().replace("-", "");
            originalFilename = replace + originalFilename;
            String time = new DateTime().toString("yyyy/MM/dd");
            originalFilename = time + "/" + originalFilename;

            PutObjectResult putObjectResult = ossClient.putObject(bucketname, originalFilename, inputStream);

            url = "https://" + bucketname + "." + endpoint + "/" + originalFilename;
        } catch (Exception ce) {
            System.out.println("上传异常--");
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
        return url;
    }
}
